/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { formType } from '@/components/form';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDigit,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
import KbUploadFile from '@/components/KbUploadFile/';
import { getFileUrl, uploadButton } from '@/components/KbUploadFile/config';
import { FormColFormat, ModalFormColFormat } from '../../_utils/index.config';
import { getTradInfo, refundReviewAdd } from '@/services/tools/refundRequest';
import { debounce, isFunction } from 'lodash';
import { message } from 'antd';
import type { Columns } from '../../_utils/type';

interface KbAddRefundExamineProps extends formType {
  record?: Columns;
  callback?: void;
}
const KbAddRefundExamine = (props: KbAddRefundExamineProps | any) => {
  const { record, callback, type, ...rest } = props;
  const formRef = useRef<ProFormInstance>();
  const [filesList, setFilesList] = useState<any[]>([]);
  // const [mustPic, updateMustPic] = useState<boolean>(false);
  const [money, setMoney] = useState<string>('0');
  const [hideWaybillNo, updateHideWaybillNo] = useState<boolean>(true);
  const [userIdRequired, setUserIdRequired] = useState<boolean>(true);

  const handleChange = (file: any) => {
    const { fileList } = file;
    if (filesList.length > fileList.length) {
      setFilesList(fileList);
    }
  };
  const onSuccess = (data: any) => setFilesList([...filesList, { url: data.url }]);
  const onChange = debounce(() => {
    const value = formRef.current?.getFieldValue('trade_number');
    getTradInfo({ trade_number: value }).then((res) => {
      const { code, data } = res;
      if (code == 0) {
        const { kb_name, user_id, money: money_ } = data;
        formRef.current?.setFieldsValue({
          kb_name,
          user_id,
        });
        setMoney(money_);
        updateHideWaybillNo(kb_name !== '微快递');
        setUserIdRequired(kb_name !== '微快递');
      }
    });
  }, 300);

  const onFinish = async (values: any) => {
    if (money && values?.money && Number(values?.money) > Number(money)) {
      message.error('退款金额不能超过实付金额');
      return;
    }
    values.pic = getFileUrl(filesList).join(';');
    refundReviewAdd(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        formRef.current?.resetFields();
        setFilesList([]);
        if (callback && isFunction(callback)) {
          callback();
        }
      } else {
        message.error(msg);
      }
    });
  };

  useEffect(() => {
    if (record) {
      if (record.pic) {
        record.pic.split(';').forEach((item: any, index: number) => {
          setFilesList([
            ...filesList,
            {
              uid: index,
              url: item,
            },
          ]);
        });
      }
      setMoney(record?.pay_money);
      updateHideWaybillNo(record.kb_name !== '微快递');
      setUserIdRequired(record.kb_name !== '微快递');
      formRef.current?.setFieldsValue({ ...record, waybillNo: record.waybill_no });
    }
    return () => {
      setFilesList([]);
    };
  }, [record]);

  const formFields = (
    <>
      <ProFormText name='id' hidden />
      <ProFormText
        label='支付流水号'
        rules={[{ required: true, message: '请输入支付流水号' }]}
        name='trade_number'
        fieldProps={{
          onChange,
        }}
      />
      <ProFormSelect
        label='产品类型'
        name='kb_name'
        disabled
        rules={[{ required: true, message: '请输入正确的产品类型' }]}
      />
      <ProFormText
        label='用户账号'
        name='user_id'
        disabled
        rules={userIdRequired ? [{ required: true, message: '请输入正确的用户账号' }] : []}
      />
      <ProFormDigit
        label='退款金额'
        name='money'
        min={0}
        max={200}
        fieldProps={{ precision: 2 }}
        placeholder='最高为200元，超过请在钉钉提交'
        extra={`该交易流水号对应实付金额${money}元`}
        rules={[{ required: true, message: '请输入退款金额' }]}
      />
      <ProFormText
        hidden={hideWaybillNo}
        label='运单号'
        name='waybillNo'
        rules={hideWaybillNo ? [] : [{ required: true, message: '请输入正确的运单号' }]}
      />
      <ProFormTextArea
        label='情况说明'
        name='trans_desc'
        rules={[{ required: true, message: '请输入情况说明' }]}
      />
      <ProForm.Item
        name='pic'
        label='图片上传'
        style={{ marginLeft: 10 }}
        validateTrigger={filesList}
        rules={[{ required: true, message: '请上传图片' }]}
      >
        <KbUploadFile
          api='/RefundReview/uploadImg'
          accept='.jpg,.png'
          listType='picture-card'
          fileList={filesList}
          onChange={handleChange}
          onCallBack={onSuccess}
          checkType='checkImg'
          showUploadList={{ showPreviewIcon: false }}
          maxCount={3}
        >
          {filesList.length < 3 ? uploadButton : ''}
        </KbUploadFile>
      </ProForm.Item>
    </>
  );

  return (
    <>
      {type === 'form' ? (
        <ProForm
          layout='horizontal'
          formRef={formRef}
          {...FormColFormat}
          {...rest}
          onFinish={onFinish}
        >
          {formFields}
        </ProForm>
      ) : (
        <ModalForm
          layout='horizontal'
          formRef={formRef}
          {...ModalFormColFormat}
          {...rest}
          onFinish={onFinish}
        >
          {formFields}
        </ModalForm>
      )}
    </>
  );
};

export default KbAddRefundExamine;
